package com.example.ResumeWorkPlatform.rest;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ResumeWorkPlatform.dao.BasicUserDao;
import com.example.ResumeWorkPlatform.dao.BasicUserEntity;
import com.example.ResumeWorkPlatform.dao.BoardDao;
import com.example.ResumeWorkPlatform.dao.BoardEntity;
import com.example.ResumeWorkPlatform.dao.DepartmentDao;
import com.example.ResumeWorkPlatform.dao.DepartmentEntity;
import com.example.ResumeWorkPlatform.dao.GerdenDao;
import com.example.ResumeWorkPlatform.dao.GerdenEntity;
import com.example.ResumeWorkPlatform.dao.WorkResumptioDao;
import com.example.ResumeWorkPlatform.dao.WorkResumptionEntity;
import com.example.ResumeWorkPlatform.service.BoardService;
import com.example.ResumeWorkPlatform.service.UserService;
import com.example.ResumeWorkPlatform.util.CheckRequestUtil;
import com.example.ResumeWorkPlatform.util.MyException;
import com.example.ResumeWorkPlatform.util.TimeFormate;



/**
 * 
 * @ClassName: BoardRest
 * @Description: 
 * @Author :chengwenixng
 * @Copyright: Smartlab411
 * @DateTime 2021-04-28 19:51:18
 */
@RestController
@RequestMapping("web/rest/board/")
public class BoardRest {
			//创建日志
			private static final Logger log = LoggerFactory.getLogger(BoardRest.class);
			@Autowired
			BoardService boardService;
			@Autowired
			private UserService userService;
			@Autowired
			GerdenDao gerdenDao;
			@Autowired
			DepartmentDao departmentDao;
			@Autowired
			BasicUserDao basicUserDao;
			@Autowired
			WorkResumptioDao workResumptioDao;
			@Autowired
			BoardDao boardDao;
			/**
			 * 根据工业园区获取今日看板数据
			 * 
			 * @Title:getAllBoardDatas
			 * @Description:
			 * @Author chengwenixng
			 * @DateTime  2021-03-29
			 * @param reqStr
			 * @return
			 */
			@RequestMapping("getAllBoardDatas")
			public JSONObject getAllDepartment(@RequestBody String reqStr) {
				log.info("getAllDepartment:" + reqStr);
				/**
				 * 预返回数据
				 */
				JSONObject return_data = new JSONObject();
				JSONObject response = new JSONObject();
				return_data.put("cmd", "getAllBoardDatas");
				return_data.put("type", "response");
				return_data.put("response", response);
				try {
					JSONObject req =CheckRequestUtil.checkReqInterface(reqStr, "getAllBoardDatas");
					JSONObject message = new JSONObject();
					// 获取当前日期
					Date eTime = new Date();
					// 获取7天前日期
					Calendar theCa = Calendar.getInstance();
					theCa.setTime(eTime);
					theCa.add(theCa.DATE, -6);
					Date sTime = TimeFormate.getDateByFormatDateYMD(TimeFormate.getFormatStrYMDByDate(theCa.getTime())); // 取出信息

					long startTime = TimeFormate.getDateByFormatDateYMD(TimeFormate.getFormatStrYMDByDate(sTime)).getTime();
					long endTime = eTime.getTime();
					
					// 获取园区id
					if (req.get("id") == null) {
						throw new MyException("请选择工业园区");
					}
					Long id= req.getLong("id");//工业园区
					//判断工业园区是否存在
					GerdenEntity gerdenId = gerdenDao.findByIdAndDelFlag(id, true);
					if (gerdenId == null) {
						throw new MyException("未找到该园区！");
					}
					/**
					 * 添加部门
					 */
					//查询工业园区是否存在
					GerdenEntity gerdenEntity = gerdenDao.findByIdAndDelFlag(id, true);
					if (gerdenEntity == null) {
						throw new MyException("未找到该园区！");
					}
					DepartmentEntity department= new DepartmentEntity();
					department.setGerdenEntity(gerdenId);
					department.setDepartmentName("财务管理");
					departmentDao.save(department);
					
					
					/**
					 * 添加用户
					 */
					Long idLong=(long) 1;
					DepartmentEntity  departmentEntityId = departmentDao.findByDepartmentIdAndDelFlag(idLong, true);

					List<BasicUserEntity> basicUserList =basicUserDao.findByDelFlag(true);

					if(basicUserList.size() <= 50) {
						for (int i = 0; i <= 50; i++) {//9代表循环九次，产生九个随机号码
				            String number = "159";//定义电话号码以139开头
				            Random random = new Random();//定义random，产生随机数
				            for (int j = 0; j < 8; j++) {
				                //生成0~9 随机数
				                number += random.nextInt(9);
				            }
				            BasicUserEntity bUserEntity =new  BasicUserEntity();
				            bUserEntity.setAccount(number);
				            bUserEntity.setPassword("123456");
				            bUserEntity.setStaffName("程文星"+i);
				            bUserEntity.setStaffNumber("666666");
				            bUserEntity.setBodyTemperature("36.5");
					   		bUserEntity.setGerdenEntity(gerdenEntity);
					   		bUserEntity.setDepartmentEntity(departmentEntityId);
				            bUserEntity.setPhone(number);
				         
					   		basicUserDao.save(bUserEntity);
				     
						}
					}
	
					/**
					 * 获取七日扫码入园情况
					 */
					List<Object[]> boardEntities =boardService.getBoardEntities(id,sTime, eTime);
					// 整理信息
					Map<Long, Integer> map = new TreeMap<>();
					JSONArray data = new JSONArray();


					for (long i = startTime; i < endTime; i = i + 86400000) {
						map.put(new Date(i).getTime(), 0);
					}
					//获取七日扫码入园情况
					for (Object[] add : boardEntities) {
						map.put(TimeFormate.getDateByFormatDateYMD(add[0].toString()).getTime(),
								Integer.valueOf(add[1].toString()));
					}
					for (Long add : map.keySet()) {
						JSONObject addData = new JSONObject();
						addData.put("time", add);
						addData.put("number", map.get(add));
						data.add(addData);
					}
					message.put("findBoardWeekIsWorks", data);
					
					/**
					 * 获取七日复工趋势
					 */
					List<Object[]> workResumption =boardService.getWorkResumptions(id,sTime, eTime);
					// 整理信息
					Map<Long, Integer> map1 = new TreeMap<>();
					JSONArray data1 = new JSONArray();

					for (long i = startTime; i < endTime; i = i + 86400000) {
						map1.put(new Date(i).getTime(), 0);
					}
					//获取七日复工趋势
					for (Object[] add1 : workResumption) {
						map1.put(TimeFormate.getDateByFormatDateYMD(add1[0].toString()).getTime(),
								Integer.valueOf(add1[1].toString()));
					}
					for (Long add1 : map1.keySet()) {
						JSONObject addData1 = new JSONObject();
						addData1.put("time", add1);
						addData1.put("number", map1.get(add1));
						data1.add(addData1);
					}
					message.put("findBoardWeekResumptions", data1);
					/**
					 * 根据园区id获取企业总人数
					 */
					List<BasicUserEntity> basicUserEntities =gerdenId.getBasicUserEntities();
					message.put("PersonalTotal", basicUserEntities.size() );
					/**
					 * 根据园区id获取员工列表
					 */
					JSONArray data3 = new JSONArray();

					for(BasicUserEntity basicUserEntity :basicUserEntities) {
						
						 JSONObject addData = new JSONObject();
						addData.put("id", basicUserEntity.getId()); // id值
						addData.put("key",basicUserEntity.getId()); // key值
						addData.put("staffName",basicUserEntity.getStaffName() != null ? basicUserEntity.getStaffName() :""); // 姓名
						addData.put("staffNumber",basicUserEntity.getStaffNumber() !=null ? basicUserEntity.getStaffNumber():""); // 工号
						addData.put("department",
								basicUserEntity.getDepartmentEntity() != null ? 
										basicUserEntity.getDepartmentEntity().getDepartmentName() : ""); // 所属部门
						addData.put("phone",basicUserEntity.getPhone() !=null ? basicUserEntity.getPhone() : ""); // 手机号
						data3.add(addData);
					}
					message.put("allStaffList", data3);
					/**
					 * 根据工业园区id获取今日员工信息
					 */
					// 获取当天开始时间和结束时间
					List<BasicUserEntity> basicUserEntities2 =boardService.getTodayBasicUserLists(id);
					message.put("TodayWorkPersonalTotal", basicUserEntities2.size() );
					/**
					 * 获取今日健康员工总数
					 */
					List<BasicUserEntity> basicUserEntities3 =userService.basicUserEntities3(id);
					message.put("TodayHealthTotal", basicUserEntities3.size() );
					/**
					 * 获取今日健康并打卡的员工总数
					 */
					List<BasicUserEntity> basicUserEntities4 =userService.basicUserEntities4(id);
					message.put("TodayHealthAndWorkTotal", basicUserEntities4.size() );
					/**
					 * 已完成隔离员工总数
					 */
					List<BasicUserEntity> basicUserEntities5 =userService.basicUserEntities5(id);
					message.put("FinishInsulateTotal", basicUserEntities5.size() );
					/**
					 * 隔离中员工总数
					 */
					List<BasicUserEntity> basicUserEntities6 =userService.basicUserEntities6(id);
					message.put("IsfinishInsulateTotal", basicUserEntities6.size() );
					/**
					 * 已员复工员工总数
					 */
					List<BasicUserEntity> basicUserEntities7 =userService.basicUserEntities7(id);
					message.put("workResumption", basicUserEntities7.size() );
					/**
					 * 有疫区接触史员工员工总数
					 */
					List<BasicUserEntity> basicUserEntities8 =userService.basicUserEntities8(id);
					message.put("Touch", basicUserEntities8.size() );
					/**
					 * 已回工作地员工
					 */
					List<BasicUserEntity> basicUserEntities9 =userService.basicUserEntities9(id);
					message.put("RturnWorkingLocation", basicUserEntities9.size() );
					/**
					 * 获取所有工业园区
					 */
					// 获取数据
					List<GerdenEntity> gerdenList = gerdenDao.findByDelFlag(true);
					JSONArray  gerdenlistArray= new JSONArray();

					//遍历返回数据
					 gerdenList.forEach((gerden) ->{
						 JSONObject addData = new JSONObject();
						addData.put("id",  gerden.getId()); // id值
						addData.put("key",  gerden.getId()); // key值
						addData.put("gerdenName",gerden.getGerdenName()); // 姓名
						addData.put("createTime",gerden.getCreateTime().getTime());
						gerdenlistArray.add(addData);
					 });
					message.put("gerdenlist", gerdenlistArray);	
					/**
					 * 获取所有部门
					 */
					List<DepartmentEntity> departmentList =gerdenId.getDepartmentList();
					JSONArray   departments= new JSONArray();
					//遍历返回数据
					for (DepartmentEntity departmentEntity : departmentList) {
						// 过滤已删除的数据
						if (!departmentEntity.isDelFlag()) {
							continue;
						}
						 JSONObject addData = new JSONObject();
							addData.put("departmentId",departmentEntity.getDepartmentId()); // id值
							addData.put("key", departmentEntity.getDepartmentId()); // key值
							addData.put("departmentName",departmentEntity.getDepartmentName()); // 部门名称
							addData.put("gerdenEntity",departmentEntity.getGerdenEntity()==null ? "尚未填写" :departmentEntity.getGerdenEntity().getGerdenName()); // 所属园区
							addData.put("createTime",departmentEntity.getCreateTime().getTime());
							departments.add(addData);
						
					}
					message.put("departmentList", departments);	
					/**
					 * 操作
					 */
					try{
						/**
						 * 获取所有人员信息
						 */
						List<BasicUserEntity>  persional= basicUserDao.findByDelFlag(true);
						if (persional == null) {
							throw new MyException("数据库中暂无数据！");
						}
						for(BasicUserEntity basicUserEntity :persional) {
							if(basicUserEntity.getWorkResumption()==false) {
								//new一个复工对象
								WorkResumptionEntity workResumptionEntity=new WorkResumptionEntity();
								//添加复工时间
								workResumptionEntity.setWorkResumptionTime(new Date());
								workResumptionEntity.setBasicUserEntity(basicUserEntity);
								workResumptionEntity.setGerdenEntity(gerdenEntity);
								workResumptioDao.save(workResumptionEntity);
								basicUserEntity.setWorkResumption(!basicUserEntity.getWorkResumption());
							}
							/**	
							 * 判断今日是否考勤
							 */
							if(basicUserEntity.getIsWork() == false) {
								//考勤
								BoardEntity boardEntity=new BoardEntity();
								boardEntity.setCeckingInTime(new Date());
								boardEntity.setBasicUserEntity(basicUserEntity);
								boardEntity.setGerdenEntity(gerdenEntity);
								boardDao.save(boardEntity);
								basicUserEntity.setIsWork(!basicUserEntity.getIsWork());
								basicUserDao.save(basicUserEntity);
							}
							basicUserEntity.setIsFeverCough(!basicUserEntity.getIsFeverCough());
							basicUserEntity.setIsWork(!basicUserEntity.getIsWork());
							basicUserEntity.setIsHealth(!basicUserEntity.getIsHealth());
							basicUserEntity.setIsRturnWorkingLocation(!basicUserEntity.getIsRturnWorkingLocation());
							basicUserEntity.setFinishInsulate(!basicUserEntity.getFinishInsulate());	
						}
				        }catch (Exception e){
				        	log.info("失败！");
				     }
					/**
					 * 返回前端数据
					 */
					
					response.put("res", true);
					response.put("message",message);
				}catch (MyException e) {
					log.error("getAllBoardDatas:" + e.getReason());
					response.put("res", false);
					response.put("exception", e.getReason());
				} catch (Exception e) {
					log.error("getAllBoardDatas:" + e.getMessage());
					response.put("res", false);
					response.put("exception", e.getMessage());
				}
				log.info("getAllBoardDatas 接口方法调用完成!");
				return return_data;
			}
			
}
